package com.ukefu.webim.web.handler.apps.bpm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.snaker.engine.SnakerEngineFacets;
import org.snaker.engine.SnakerHelper;
import org.snaker.engine.access.Page;
import org.snaker.engine.access.QueryFilter;
import org.snaker.engine.entity.HistoryOrder;
import org.snaker.engine.entity.HistoryTask;
import org.snaker.engine.entity.Process;
import org.snaker.engine.entity.Task;
import org.snaker.engine.helper.AssertHelper;
import org.snaker.engine.model.ProcessModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;
import com.ukefu.util.Menu;
import com.ukefu.webim.service.repository.MetadataRepository;
import com.ukefu.webim.service.repository.OrganRepository;
import com.ukefu.webim.service.repository.ProcessContentRepository;
import com.ukefu.webim.service.repository.UserRepository;
import com.ukefu.webim.web.handler.Handler;
import com.ukefu.webim.web.model.Organ;
import com.ukefu.webim.web.model.User;

@Controller
@RequestMapping("/apps/bpm")
public class BpmInstanceController extends Handler{
	
	@Autowired
	private ProcessContentRepository processContentRes ;
	
	@Autowired
	private MetadataRepository metadataRes ;
	
	@Autowired
	private SnakerEngineFacets facets;
	
	@Autowired
	private OrganRepository organRes ;
	
	@Autowired
	private UserRepository userRes ;
	
	@RequestMapping(value="/instance")  
	@Menu(type = "bpm" , subtype = "instance" , access = false )
    public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String displayName){  
    	QueryFilter filter = new QueryFilter();
		if(!StringUtils.isBlank(displayName)) {
			filter.setDisplayName(displayName);
		}
    	Page<HistoryOrder> page = new Page<HistoryOrder>(getPs(request));
    	page.setPageNo(super.getP(request));
		facets.getEngine().query().getHistoryOrders(page, filter);
		map.addAttribute("instanceList", page);
    	return request(super.createAppsTempletResponse("/apps/business/bpm/instance"));
    }
    
    @RequestMapping(value="/display")  
    @Menu(type = "bpm" , subtype = "instance" , access = false )
    public ModelAndView display(ModelMap map ,HttpServletRequest request , @Valid String processid , @Valid String orderid){  
    	HistoryOrder order = facets.getEngine().query().getHistOrder(orderid);
    	
    	List<HistoryTask> tasks = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(orderid));
    	List<String> ids = new ArrayList<String>();
    	for(HistoryTask task : tasks){
    		ids.add(task.getOperator()) ;
    	}
    	List<User> users = userRes.findByIdInAndOrgi(ids,super.getOrgi(request)) ;
    	for(HistoryTask task : tasks){
    		for(User user : users){
    			if(user.getId().equals(task.getOperator())){
    				task.setOperator(user.getUsername()+"（"+user.getUname()+"）"); break ;
    			}
    		}
    	}
    	
		map.addAttribute("tasks", tasks);
		map.addAttribute("processid", processid);
		map.addAttribute("orderid", orderid);
		map.addAttribute("order", order);
		
		return request(super.createAppsTempletResponse("/apps/business/bpm/display"));
    }
    
    @RequestMapping(value="/instance/display")  
    @Menu(type = "bpm" , subtype = "instance" , access = false )
    public ModelAndView instancedisplay(ModelMap map ,HttpServletRequest request , @Valid String processid , @Valid String orderid){  
    	HistoryOrder order = facets.getEngine().query().getHistOrder(orderid);
    	
    	List<HistoryTask> tasks = facets.getEngine().query().getHistoryTasks(new QueryFilter().setOrderId(orderid));
    	List<String> ids = new ArrayList<String>();
    	for(HistoryTask task : tasks){
    		ids.add(task.getOperator()) ;
    	}
    	List<User> users = userRes.findByIdInAndOrgi(ids,super.getOrgi(request)) ;
    	for(HistoryTask task : tasks){
    		for(User user : users ){
        		if(task.getOperator()!=null && task.getOperator().equals(user.getId())){
        			task.setOperator(user.getUsername()+"（"+user.getUname()+"）"); break ;
        		}
        	}
    		if(task.getVariableMap()!=null){
    			task.setOptype((String)task.getVariableMap().get("optype"));
    		}
    	}
    	
    	
		map.addAttribute("tasks", tasks);
		map.addAttribute("processid", processid);
		map.addAttribute("orderid", orderid);
		map.addAttribute("order", order);
		
		return request(super.createRequestPageTempletResponse("/apps/business/bpm/instancedisplay"));
    }
    
    @RequestMapping(value="/json")  
    @Menu(type = "bpm" , subtype = "instance" , access = false )
    public ModelAndView json(ModelMap map ,HttpServletRequest request , HttpServletResponse response, @Valid String processid , @Valid String orderid){  
    	List<Task> tasks = null;
        if(StringUtils.isNotEmpty(orderid)) {
            tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderid));
        }
        Process process = facets.getEngine().process().getProcessById(processid);
        AssertHelper.notNull(process);
        ProcessModel model = process.getModel();
        Map<String, String> jsonMap = new HashMap<String, String>();
        if(model != null) {
            jsonMap.put("process", SnakerHelper.getModelJson(model));
        }

        //{"activeRects":{"rects":[{"paths":[],"name":"任务3"},{"paths":[],"name":"任务4"},{"paths":[],"name":"任务2"}]},"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}}
        if(tasks != null && !tasks.isEmpty()) {
            jsonMap.put("active", SnakerHelper.getActiveJson(tasks));
        }
        
        map.addAttribute("json" , JSONUtils.toJSONString(jsonMap).toString()) ;
        response.setContentType("application/json; charset=utf-8");
        return request(super.createRequestPageTempletResponse("/apps/business/bpm/viewjson"));
    }
    
    @RequestMapping(value="/task/tip")  
    @Menu(type = "bpm" , subtype = "instance" , access = false )
    public ModelAndView tasktip(ModelMap map , HttpServletRequest request , HttpServletResponse response, @Valid String taskname , @Valid String orderid){  
    	List<Task> tasks = facets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderid));
        StringBuilder builder = new StringBuilder();
        String createTime = "";
        for(Task task : tasks) {
            if(task.getTaskName().equalsIgnoreCase(taskname)) {
                String[] actors = facets.getEngine().query().getTaskActorsByTaskId(task.getId());
                if(actors!=null){
	                for(String actor : actors) {
	                	Organ organ = organRes.findByIdAndOrgi(actor, super.getOrgi(request)) ;
	                	if(organ!=null){
	                		builder.append(organ.getName()).append(",");
	                	}else{
	                		User user = userRes.findByIdAndOrgi(actor, super.getOrgi(request)) ;
	                		if(user!=null){
	                			builder.append(user.getUsername()).append("（").append(user.getUname()).append("）").append(",");
	                		}
	                	}
	                }
                }
                createTime = task.getCreateTime();
                map.put("taskname", taskname);
            }
        }
        if(builder.length() > 0) {
            builder.deleteCharAt(builder.length() - 1);
        }
        map.put("actors", builder.toString());
        map.put("createTime", createTime);
        return request(super.createRequestPageTempletResponse("/apps/business/bpm/tasktip"));
    }
}